//
//  HomeTableController.swift
//  SinaBlog
//
//  Created by ChenWei on 15/10/2.
//  Copyright © 2015年 cw. All rights reserved.
//

import UIKit
import SDWebImage

class HomeTableController: BaseTableViewController {
    /// 导航栏中间标题
    var titleBtn : TitleButton?
    
    /// 存储所有的微博数据
    private var statuses: [Status]? {
        didSet {
            // 刷新表格
            tableView.reloadData()
        }
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()

        // 1. 判断是否是访客视图
        if !isLogin {
            vistorView?.setupVistorInfo(isHome:true, imageName: "visitordiscover_feed_image_house", info: "首页:关注一些人,回到这里会有很多的惊喜等着你的!!请行动起来吧! 我的小孩")
            vistorView?.startAnimator()
            return  // 一定要ruturn :如果是访客界面下面的代码就不用执行了,(下面代码不属于访客界面)
        }
        // 2. 设置导航条
        setupNav()
        
        // 3.加载微博数据
        loadData()
        
//        tableView.rowHeight = 300
//        tableView.estimatedRowHeight = 500
        // 告诉系统自动计算行高, 注意: 一定要先预估一个行高才能正确计算
//        tableView.rowHeight = UITableViewAutomaticDimension

        // 4.注册Cell
        tableView.registerClass(CWHomeNormalCell.self, forCellReuseIdentifier: CellReusabeID.normalCell.rawValue)
        
        tableView.registerClass(CWHomeForwardCell.self, forCellReuseIdentifier: CellReusabeID.forwardCell.rawValue)
        
        // 5.去除分隔线
        tableView.separatorStyle = UITableViewCellSeparatorStyle.None
    }
    
    // MARK: - UITableViewDataSource
    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return statuses?.count ?? 0
    }
    
    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        // 1.创建cell
        let status = statuses![indexPath.row]
        let reusableID = CellReusabeID.getReusableCellID(status)
        let cell = tableView.dequeueReusableCellWithIdentifier(reusableID) as! CWHomeTableViewCell
        
        // 2.给cell传递数据
        cell.status = statuses![indexPath.row]

        return cell
    }
    
    // MARK: - UITableViewDelegate
    /// 缓存行高字典(用status.id作为key)
    private var rowHeightsCache = [Int:CGFloat]()
    override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
        // 1.取出模型
        let status = statuses![indexPath.row]
        
        // 2.根据模型拿到重用标识并创建对应的cell
        let reusableID = CellReusabeID.getReusableCellID(status)
        let cell = tableView.dequeueReusableCellWithIdentifier(reusableID) as! CWHomeTableViewCell
        
        // 3.缓存中有行高
        if let rowHeight = rowHeightsCache[status.id] {
            return rowHeight
        }
        
        // 4.如果没有缓存过行高,计算行高
        let rowHeight = cell.rowHeight(status)
        // 5.缓存行高
        rowHeightsCache[status.id] = rowHeight
        
        return rowHeight
    }
    
    // MARK: - 内部控制方法
    /// 加载微博数据
    private func loadData() {
        let parameters = ["access_token": UserAccount.loadAccount()!.access_token!]
        NetworkTools.shareNetworkTools().GET("2/statuses/home_timeline.json", parameters: parameters, success: { (_, JSON) -> Void in
//            NSLog(message: JSON)
            // 1.微博数据有值
            if let dictArr = JSON["statuses"] {
                var models = [Status]()
                for dict in dictArr as! [[String: AnyObject]] {
                    models.append(Status(dict: dict))
                }
                
                // 1.1 所有weibo的图片下载完成后用statuses存储所有微博数据
                self.cacheImages(models)
            }
            }) { (_, error) -> Void in
                NSLog(message: error)
        }
    }
    
    /**
     缓存所有微博的配图,并用微博模型接收所有微博数据statuses
     - parameter models: 微博模型数组
     */
    private func cacheImages(models:[Status]) {
        // 1.判断模型数组是否为空
        guard models.count != 0 else {
            return
        }
        
        // 创建一个组
        let group = dispatch_group_create()
        
        // 2.遍历数组,下载图片
        for status in models {
            
            // 2.1判断是否有配图
            guard status.pic_urls?.count != 0 else {
                continue
            }
            
            // 2.2下载图片
            for pictDict in status.pic_urls! {
                
                // 2.2.1将当前下载图片的操作加入到组中
                dispatch_group_enter(group)
                
                let url = NSURL(string: pictDict["thumbnail_pic"] as! String)
                SDWebImageManager.sharedManager().downloadImageWithURL(url, options: [], progress: nil, completed: { (_, _, _, _, _) -> Void in
                    
                    // 2.2.2下载完成后将当前图片的下载操作从组中移除
                    dispatch_group_leave(group)
                })
            }
        }
        
        // 3.监听所有下载完成后操作
        dispatch_group_notify(group, dispatch_get_main_queue()) { () -> Void in
            self.statuses = models
        }
    }

    /// 监听leftBarButtonItem点击
    func leftBarButtonItemClick() {
        print(__FUNCTION__)
    }
    
    /// 监听leftBarButtonItem点击
    func rightBarButtonItemClick() {
        let sb = UIStoryboard(name: "QRCodeViewController", bundle: nil)
        let vc = sb.instantiateInitialViewController()
        presentViewController(vc!, animated: true, completion: nil)
        print(__FUNCTION__)
    }
    
    /// 添加导航条
    func setupNav() {
        // 1.利用对象方法:左边导航按钮
        navigationItem.leftBarButtonItem = UIBarButtonItem().createBarButtonItem("navigationbar_friendattention", target: self, action: Selector("leftBarButtonItemClick"))
        
        // 2.利用便利构造方法:右边导航按钮
        navigationItem.rightBarButtonItem = UIBarButtonItem(imageName: "navigationbar_pop", target: self, action: Selector("rightBarButtonItemClick"))
        
        // 3.中间titleView
        let btn = TitleButton()
        titleBtn = btn
        btn.setTitle("极度人生" + " ", forState: UIControlState.Normal)
        btn.setImage(UIImage(named: "navigationbar_arrow_up"), forState: UIControlState.Normal)
        btn.setImage(UIImage(named: "navigationbar_arrow_down"), forState: UIControlState.Selected)
        
        btn.addTarget(self, action: Selector("titleButtonClick:"), forControlEvents: UIControlEvents.TouchUpInside)
        
        navigationItem.titleView = btn
    }
    
    // MARK: - 内部控制方法
    /// 监听titleButton的点击
    func titleButtonClick(titleButton: TitleButton) {
        // 1.创建菜单控制器
        let sb = UIStoryboard(name: "PopoverViewController", bundle: nil)
        let vc = sb.instantiateInitialViewController()!
        
        // 2.设置转场代理对象
        vc.transitioningDelegate = self.popoverPresentation
        
        // 4. 设置显示样式
        vc.modalPresentationStyle = UIModalPresentationStyle.Custom
        
        // 5.弹出转场界面
        presentViewController(vc, animated: true, completion: nil)
        
    }
    
    /// 修改titleButton的状态
    func changeTitleButtonChangeState() {
        titleBtn!.selected = !titleBtn!.selected
    }
    
    // MARK:- 懒加载
    lazy var popoverPresentation: PopoverPresentationController = {
        let vc = PopoverPresentationController()
        // 设置转场界面的大小
        vc.presentedViewFrame = CGRectMake(100, 56, 200, 400)
        
        // 注册通知,监听弹出菜单的展现和消失
        NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("changeTitleButtonChangeState"), name: CWNotificationPopoverViewDidShow, object: nil)
        NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("changeTitleButtonChangeState"), name: CWNotificationPopoverViewDidDismiss, object: nil)
        return vc
    }()
    
    // MARK: - 内存警告
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        rowHeightsCache.removeAll()
    }
    
    override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
        let cell = tableView.cellForRowAtIndexPath(indexPath) as! CWHomeTableViewCell
        NSLog(message: cell.pictureView.calculatePictureCollectionCellSize())
        NSLog(message: cell.pictureView.frame)
        NSLog(message: cell.pictureView.contentSize)
        NSLog(message: cell.status?.pic_URLS)
    }
}




